//
//  DutyMapViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/11/10.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "DutyMapViewController.h"
#import "GoOutSearchTableViewCell.h"
#import<BaiduMapAPI_Map/BMKMapView.h>
#import<BaiduMapAPI_Location/BMKLocationService.h>
#import<BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import <BaiduMapAPI_Search/BMKSuggestionSearch.h>
#import<BaiduMapAPI_Search/BMKSuggestionSearchOption.h>
#import <BaiduMapAPI_Map/BMKPinAnnotationView.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>


@interface DutyMapViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,BMKSuggestionSearchDelegate>
{
    BMKMapView *_mapView;  //地图
    BMKLocationService *_locService;  //定位
    UIView * _searchView;//搜索框
    BMKGeoCodeSearch *_geocodesearch; //地理编码主类，用来查询、返回结果信息
    UITapGestureRecognizer *_tapGesture;//手势
    UIView *_searchBackView;//搜索view
    UITableView *_searchTableView;//搜索结果列表
    BMKSuggestionSearch *_suggestionSearch;
    UIView *_alphaView;//黑色背景框
}
@property (nonatomic,assign) BOOL isMoveSearch;//是否是移动地图搜索
@property (nonatomic,strong) NSString *nowAddressStr;//当前位置
@property (nonatomic,strong) UISearchBar * searchBar;//搜索栏
@property (nonatomic,strong) NSString *placeX;//纬度
@property (nonatomic,strong) NSString *placeY;//经度
@property (nonatomic,strong) NSMutableArray *keyListArray;//详细地址搜索列表
@property (nonatomic,strong) NSMutableArray *cityListArray;//所在城市搜索列表
@property (nonatomic,strong) NSMutableArray *districtListArray;//所在区搜索列表
@end

@implementation DutyMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!_mapView) {
        [self creatView];
    }
    self.navigationController.navigationBar.hidden=YES;
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}

- (void)addTapGestureRecognizer{
    //避免手势混乱 所以先移除
    if (_tapGesture) {
        [_mapView removeGestureRecognizer:_tapGesture];
        _tapGesture=nil;
    }
    _tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClick)];
    [_mapView addGestureRecognizer:_tapGesture];
}

- (void)removeTapGestureRecognizer{
    [self.view endEditing:YES];
    [_mapView removeGestureRecognizer:_tapGesture];
    _tapGesture=nil;

}

#pragma mark -手势的响应事件
- (void)tapGestureClick{
    [self removeTapGestureRecognizer];
}

#pragma mark -确定点击事件
- (void)beginSearchItemsForTableView{
    [self.view endEditing:YES];
    if (_searchBar.text.length==0) {
        [LZXHelper postMessageWithText:@"您还没有输入搜索内容!" View:self.view];
        return;
    }
    if (_myBlock) {
        _myBlock(_searchBar.text,_cityName,_placeX,_placeY,_nowAddressStr);
    }
    [self backClick];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    self.navigationController.navigationBar.hidden=NO;
}

#pragma mark -搜索结果列表
- (void)creatSearchTableView{
    _searchBackView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    _searchBackView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_searchBackView];
    
    _alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 60, _searchBackView.width, _searchBackView.height)];
    _alphaView.alpha=0.4;
    _alphaView.backgroundColor=[UIColor blackColor];
    [_searchBackView addSubview:_alphaView];
    
    //点击手势
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TwoTapGestureRecognizer:)];
    tapGesture.delegate=self;
    [tapGesture setNumberOfTapsRequired:1];
    [tapGesture setNumberOfTouchesRequired:1];
    [_alphaView addGestureRecognizer:tapGesture];
    
    _searchTableView=[[UITableView alloc]initWithFrame:CGRectMake(10, 60, _searchBackView.width-20, 300) style:UITableViewStylePlain];
    //_searchTableView.backgroundColor=[UIColor clearColor];
    _searchTableView.delegate=self;
    _searchTableView.dataSource=self;
    _searchTableView.tag=111;
    _searchTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    //[self addTableViewUpdateRefresh:self.tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [_searchBackView addSubview:_searchTableView];
    
}

#pragma mark -手势点击时间
-(void)TwoTapGestureRecognizer:(UIGestureRecognizer*)gr{
    [self.view endEditing:YES];
    if (_searchBackView) {
        [_searchBackView removeFromSuperview];
        _searchBackView=nil;
    }
    [_alphaView removeGestureRecognizer:_tapGesture];
}

- (void)creatView{
    //添加地图视图
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    _mapView.showsUserLocation = YES; //是否显示定位图层（即我的位置的小圆点）
    _mapView.zoomLevel = 18;//地图显示比例
    _mapView.mapType = BMKMapTypeStandard;//设置地图为空白类型
    _mapView.showMapScaleBar = YES;
    //自定义比例尺的位置
    _mapView.mapScaleBarPosition = CGPointMake(_mapView.frame.size.width - 70, _mapView.frame.size.height - 68);
    [self.view addSubview:_mapView];
    
    BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc]init];
    displayParam.isRotateAngleValid = true;//跟随态旋转角度是否生效
    displayParam.isAccuracyCircleShow = false;//精度圈是否显示
    displayParam.locationViewImgName= @"icon";//定位图标名称
    displayParam.locationViewOffsetX = 0;//定位偏移量(经度)
    displayParam.locationViewOffsetY = 0;//定位偏移量（纬度）
    [_mapView updateLocationViewWithParam:displayParam];

    
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    
    _geocodesearch.delegate = self;
    
//    if (_addressStr) {
//        BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
//        geocodeSearchOption.city= _cityName;
//        geocodeSearchOption.address = _addressStr;
//        BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
//        if(flag)
//        {
//            NSLog(@"geo检索发送成功");
//        }
//        else
//        {
//            NSLog(@"geo检索发送失败");
//        }
//    }else{
        [self startLocation];//开始定位方法
//    }
    
    UIImageView *mapImage=[MyControl creatImageViewWithFrame:CGRectMake((IPHONE_WIDTH-20)/2, IPHONE_HEIGHT/2-25, 20, 25) imageName:@"icon_makernew2@2x"];
    [self.view addSubview:mapImage];
    
    //返回按钮
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(10, IPHONE_HEIGHT-60, 40, 40)];
    backView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:backView];
    
    UIView *alphoView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, backView.width, backView.height)];
    alphoView.alpha=0.4;
    alphoView.backgroundColor=[UIColor blackColor];
    [backView addSubview:alphoView];
    
    UIButton *backButton=[UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame=CGRectMake(0, 0, backView.width, backView.height);
    [backButton setImage:[UIImage imageNamed:@"icon1_1@2x"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:backButton];
    
    //    if (_searchView) {
    //        //防止搜索按钮多次被点击
    //        return;
    //    }
    //    _grayButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 64, IPHONE_WIDTH, IPHONE_HEIGHT-64)];
    //    [_grayButton setBackgroundColor:COLOR(106, 107, 108, 0.7)];
    //    [_grayButton addTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:_grayButton];
    //搜索框
    _searchView = [[UIView alloc]initWithFrame:CGRectMake(10, 20, IPHONE_WIDTH-20, 40)];
    _searchView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_searchView];
    //textField
    
    //searchBar
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, _searchView.width-60, 40)];
    _searchBar.placeholder = @"请输入搜索内容";
    //    _searchBar.borderStyle = UITextBorderStyleRoundedRect;
    //    _searchBar.font = FONT_14;
    //    _searchBar.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchBar.delegate = self;
    _searchBar.searchBarStyle=UISearchBarStyleMinimal;
    _searchBar.returnKeyType = UIReturnKeyGo;
    [_searchView addSubview:_searchBar];
    //startSearchButton
    
    //搜索按钮
    UIButton * searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setTitle:@"确定" forState:UIControlStateNormal];
    [searchButton setTitleColor:COLOR_MIDBLUE forState:UIControlStateNormal];
    searchButton.titleLabel.font = FONT_14;
    [_searchView addSubview:searchButton];
    //[searchButton setBackgroundColor:[UIColor yellowColor]];
    searchButton.frame = CGRectMake(_searchBar.x+_searchBar.width, _searchBar.y, 60, 40);
    searchButton.layer.cornerRadius = 8;
    searchButton.layer.masksToBounds = YES;
    [searchButton addTarget:self action:@selector(beginSearchItemsForTableView) forControlEvents:UIControlEventTouchUpInside];
}

- (void)tapPress:(UIGestureRecognizer*)gestureRecognizer {
    

}

//开始定位
-(void)startLocation
{
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    _locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    //启动LocationService
    [_locService startUserLocationService];
}


//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    NSLog(@"heading is %@",userLocation.heading);
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    self.placeX=[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude];
    self.placeY=[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude];
    //普通态
    //以下_mapView为BMKMapView对象
    [_mapView updateLocationData:userLocation]; //更新地图上的位置
    _mapView.centerCoordinate = userLocation.location.coordinate; //更新当前位置到地图中间
    //地理反编码
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];

    if(flag){
        NSLog(@"反geo检索发送成功");
        [_locService stopUserLocationService];
    }else{
        NSLog(@"反geo检索发送失败");
    }
}

#pragma mark -地图区域改变完成后会调用此接口
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{

    //CGPoint touchPoint = [gestureRecognizer locationInView:_mapView];//这里touchPoint是点击的某点在地图控件中的位置
    //取地图的中心
    CLLocationCoordinate2D touchMapCoordinate =
    [_mapView convertPoint:self.view.center toCoordinateFromView:_mapView];//这里touchMapCoordinate就是该点的经纬度了
    //地理反编码
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = touchMapCoordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    
    if(flag){
        NSLog(@"反geo检索发送成功");
        [_locService stopUserLocationService];
    }else{
        NSLog(@"反geo检索发送失败");
    }
}

#pragma mark -------------地理反编码的delegate---------------
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"address:%@----%@",result.addressDetail,result.address);
    _cityName=[result.addressDetail.city copy];
    self.placeX=[NSString stringWithFormat:@"%f",result.location.latitude];
    self.placeY=[NSString stringWithFormat:@"%f",result.location.longitude];
    if (!self.isMoveSearch) {
        self.isMoveSearch=YES;
        _nowAddressStr=result.address;
    }else{
        self.searchBar.text=result.address;
    }
//    //增加气泡
//    BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
//    item.coordinate = result.location;
//    item.title = result.address;
//    [_mapView addAnnotation:item];
//    _mapView.centerCoordinate = result.location;
    //addressDetail:     层次化地址信息
    //address:    地址名称
    //businessCircle:  商圈名称
    // location:  地址坐标
    //  poiList:   地址周边POI信息，成员类型为BMKPoiInfo
}



#pragma mark -检索结果
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        _mapView.centerCoordinate = result.location; //更新当前位置到地图中间
        NSLog(@"address:----%@",result.address);
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

#pragma mark -建议的地点列表
- (void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:(BMKSuggestionResult*)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        
        self.keyListArray = [NSMutableArray arrayWithArray:result.keyList];
        self.cityListArray= [NSMutableArray arrayWithArray:result.cityList];
        self.districtListArray=[NSMutableArray arrayWithArray:result.districtList];
        if (!_searchBackView) {
            [self creatSearchTableView];
        }else{
            [_searchTableView reloadData];
        }
        if (self.keyListArray.count==0) {
            //增加提示语
            [self addReminderViewWithFrame:_searchTableView.frame msg:@"没有搜索到结果！" backView:_searchTableView];
        }else{
            //移除提示语
            [self removeReminderView];
        }
//        self.cityListArray = result.cityList;
//        self.districtListArray = result.districtList;
        
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

//定位失败
- (void)didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"error:%@",error);
}

#pragma mark -searchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if (!_suggestionSearch) {
        _suggestionSearch=[BMKSuggestionSearch new];
        _suggestionSearch.delegate=self;
    }
    //建议列表
    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
    option.cityname = _cityName?_cityName:@"";
    option.keyword  = searchBar.text;
    BOOL flag = [_suggestionSearch suggestionSearch:option];
    if(flag)
    {
        NSLog(@"建议检索发送成功");
    }
    else
    {
        NSLog(@"建议检索发送失败");
    }
    [self.view endEditing:YES];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [self addTapGestureRecognizer];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    [self removeTapGestureRecognizer];
    return YES;
}

//- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
//    if (!_suggestionSearch) {
//        _suggestionSearch=[BMKSuggestionSearch new];
//        _suggestionSearch.delegate=self;
//    }
//    //建议列表
//    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
//    option.cityname = _cityName?_cityName:@"";
//    option.keyword  = searchBar.text;
//    BOOL flag = [_suggestionSearch suggestionSearch:option];
//    if(flag)
//    {
//        NSLog(@"建议检索发送成功");
//    }
//    else
//    {
//        NSLog(@"建议检索发送失败");
//    }
//    return YES;
//}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (!_suggestionSearch) {
        _suggestionSearch=[BMKSuggestionSearch new];
        _suggestionSearch.delegate=self;
    }
    //建议列表
    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
    option.cityname = _cityName?_cityName:@"";
    option.keyword  = searchBar.text;
    BOOL flag = [_suggestionSearch suggestionSearch:option];
    if(flag)
    {
        NSLog(@"建议检索发送成功");
    }
    else
    {
        NSLog(@"建议检索发送失败");
    }
}

//根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSString *AnnotationViewID = @"annotationViewID";
    //根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
    BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
        annotationView.image=[UIImage imageNamed:@"icon_mark@2x"];
    }
    
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    annotationView.canShowCallout = YES;
    return annotationView;
}

#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.keyListArray.count;
    //    return _newsListModel.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        //搜索结果列表
    NSString *cellID=@"GoOutSearchTableViewCell";
    GoOutSearchTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell=[[GoOutSearchTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID width:_searchTableView.width];
    }
//    AddressSearchModel *searchModel=_searchListModel.dataArr[indexPath.row];
    cell.addressLabel.text=self.keyListArray[indexPath.row];
    cell.cityLabel.text=[NSString stringWithFormat:@"%@ %@",self.cityListArray[indexPath.row],self.districtListArray[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _searchBar.text=self.keyListArray[indexPath.row];
    _cityName=self.cityListArray[indexPath.row];
    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    geocodeSearchOption.city= self.cityListArray[indexPath.row];
    geocodeSearchOption.address = self.keyListArray[indexPath.row];
    BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
    if(flag)
    {
        NSLog(@"geo检索发送成功");
    }
    else
    {
        NSLog(@"geo检索发送失败");
    }
    [self.view endEditing:YES];
    if (_searchBackView) {
        [_searchBackView removeFromSuperview];
        _searchBackView=nil;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
